package com.neusoft.neuiotms.dcam.config;

import java.util.Map;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import com.neusoft.bizcore.activiti.user.ActivitiUserDetail;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.auth.common.service.AuthUserDetailsService;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.utils.id.BaseIdGenerator;
import com.neusoft.bizcore.web.utils.id.DefaultIdGenerator;
import com.neusoft.neuiotms.micro.auth.AuthMicroService;

@Configuration
@ComponentScan
public class DcamConfiguration {

    @Bean
    @ConditionalOnMissingBean(AuthUserDetailsService.class)
    public AuthUserDetailsService authUserDetailsService(final AuthMicroService authMicroService) {
        return username -> {
            final ResultDTO<UserBean> result = authMicroService.loadUserByUsername(username);
            return result.getData();
        };
    }

    @Bean
    public BaseIdGenerator planCodeGenerator() {
        return new DefaultIdGenerator(0, "PD");
    }

    @Bean
    public BaseIdGenerator dutyCodeGenerator() {
        return new DefaultIdGenerator(0, "RW");
    }

    @Bean
    @ConditionalOnClass(ActivitiUserDetail.class)
    @ConditionalOnMissingBean
    public ActivitiUserDetail userAdapter(final AuthMicroService authMicroService) {
        final ActivitiUserDetail adapter = new ActivitiUserDetail() {
            @Override
            public UserBean getUserInfo(final String userName) {
                final ResultDTO<UserBean> result = authMicroService.loadUserByUsername(userName);
                return result.getData();
            }

            @Override
            public Map<String, Object> getRoleInfo(final String code) {
                return authMicroService.roleByCode(code).getData();
            }
        };
        return adapter;
    }

}
